//
//  HTSearchTruckVC.m
//  TruckUser
//
//  Created by Ting Han on 2017/10/16.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTSearchTruckVC.h"

#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <MapKit/MapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

#import "HTMyAnnotation.h"
#import "HTMyAnnotationView.h"
#import "HTAnnotationModel.h"

//弹框
//出发地，目的地
#import "HTAreaChoiceView.h"
//车长车型
#import "HTScanTruckType.h"
#import "HTRefreshMoreModel.h"
#import "HTMLocationManager.h"

@interface HTSearchTruckVC ()<MAMapViewDelegate,HTAreaChoiceViewDelegate,HTScanTruckTypeDelegate,AMapSearchDelegate>
@property (weak, nonatomic) IBOutlet UIView *truckTypeView;
@property (weak, nonatomic) IBOutlet UIImageView *truckTypeImageView;
@property (weak, nonatomic) IBOutlet UILabel *truckTypeLabel;
@property (weak, nonatomic) IBOutlet UIView *startView;
@property (weak, nonatomic) IBOutlet UIImageView *startImageView;
@property (weak, nonatomic) IBOutlet UILabel *startLabel;

@property (nonatomic,strong) NSMutableArray *dataSource;

@property (nonatomic,strong) NSMutableArray <HTMyAnnotation*>*annotations;

@property (weak, nonatomic) IBOutlet UIView *map;

@property (nonatomic,strong) MAMapView *mapView;
@property (nonatomic,strong) AMapSearchAPI *search;

//弹框
@property (nonatomic,strong) HTAreaChoiceView *areaChoiceView;
@property (nonatomic,strong) HTScanTruckType *truckLengthTypeView;

#pragma mark --- 数据处理
//弹框数据
@property (nonatomic,strong) NSMutableArray *selectedLengthData;
@property (nonatomic,strong) HTTruckTypeModel *selectedTruckType;
@property (nonatomic,strong) HTTruckTypeModel *selectedGoodsType;
@property (nonatomic,assign) BOOL isLessThanTruck;

@property (nonatomic,strong) NSString *startAddress;
@property (nonatomic,strong) NSString *isEmptyString;
@property (nonatomic,strong) NSString *lengthString;
@property (nonatomic,strong) NSString *truckTypeString;


@property (nonatomic,assign) NSInteger pageNumber;
@property (nonatomic,strong) HTRefreshMoreModel *refreshMoreModel;


@end

@implementation HTSearchTruckVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadMapView];
    [self tapGesture];
    self.isEmptyString = @"0";
    self.lengthString = @"0";
    self.truckTypeString = @"";
    [self loadLocation];
    self.pageNumber = 1;
   
}
#pragma mark --- 定位
- (void)loadLocation{
    if ([[HTMLocationManager singleInstance] getCurrentAddress].length <= 0) {
        //定位请求
        [self requestLocation];
        self.startLabel.text = @"北京";
        self.startAddress = self.startLabel.text;
    }else{
        self.startLabel.text = [[HTMLocationManager singleInstance] getCurrentAddress];
        self.startAddress = self.startLabel.text;
       // [self panMap];
        [self netLoadData];
    }
}
- (void)requestLocation{
    [[HTMLocationManager singleInstance]requestLocationCompletionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
           // [self panMap];
            [self netLoadData];
            if (error.code == AMapLocationErrorLocateFailed)
            {
               
                [HTShowUtil showMessage:@"定位失败"];
                return;
            }
        }
        if (regeocode)
        {
            if (regeocode.city == nil || regeocode.city.length <= 0) {
                self.startLabel.text = @"北京";
                self.startAddress = self.startLabel.text;
                return;
            }
            [HTMLocationManager singleInstance].currentCity = regeocode.city;
            [HTMLocationManager singleInstance].currentProvince = regeocode.province;
            self.startLabel.text =  [[HTMLocationManager singleInstance]getCurrentAddress];
            self.startAddress = self.startLabel.text;
           // [self panMap];
            [self netLoadData];
        }
    }];
}
#pragma mark --- 界面绘制
- (void)tapGesture{
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
    [self.startView addGestureRecognizer:tap1];
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
    [self.truckTypeView addGestureRecognizer:tap3];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _mapView.delegate = nil;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     _mapView.delegate = self;
   
}
- (NSMutableArray<HTMyAnnotation *> *)annotations{
    if (!_annotations) {
        _annotations = [NSMutableArray array];
    }
    return _annotations;
}
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
#pragma mark --- mapView
- (void)loadMapView{
    _mapView = [[MAMapView alloc] initWithFrame:self.map.bounds];
    ///把地图添加至view
    [self.map addSubview:_mapView];
    _mapView.mapType = MAMapTypeStandard;
    _mapView.showsUserLocation = YES;
    _mapView.mapType = MAMapTypeStandard;
    // 设置成NO表示关闭指南针；YES表示显示指南针
    _mapView.showsCompass= NO;
    //设置成NO表示不显示比例尺；YES表示显示比例尺
    _mapView.showsScale= NO;
    [_mapView setZoomLevel:16.1 animated:YES];
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    self.mapView.delegate = self;
    self.search = [[AMapSearchAPI alloc]init];
    self.search.delegate = self;
    
}
- (void)mapView:(MAMapView *)mapView mapDidZoomByUser:(BOOL)wasUserAction{
   
}
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    if ([annotation isKindOfClass:[HTMyAnnotation class]]) {
        MAAnnotationView *view = [(HTMyAnnotation *)annotation getAnnotationView:mapView];
        return view;
    }
    return nil;
}
- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response{
    if (response.geocodes.count == 0)
    {
        return;
    }
    AMapGeoPoint *point = response.geocodes[0].location;
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(point.latitude, point.longitude) animated:YES];
}

#pragma mark --- 选中起始地，目的地，车长车型部分
- (void)didTapGesture:(UITapGestureRecognizer *)sender{

    switch ([sender view].tag) {
        case 111://出发地
        {
            [self removeTruckLengthTypeView];
            if (self.areaChoiceView && self.areaChoiceView.areaChoiceType == HTAreaChoiceTypeStart) {//点击了同一个,收起
                [self removeAreaChoiceView];
                //设置tab选中状态
                [self setTabViewWithIndex:3];
                return;
            }
            if (self.areaChoiceView && self.areaChoiceView.areaChoiceType == HTAreaChoiceTypeDestination) {//同一个View，但是类型不同，刷新数据
                self.areaChoiceView.areaChoiceType = HTAreaChoiceTypeStart;
                [self.areaChoiceView reloadAllData];
                [self setTabViewWithIndex:0];
                return;
            }
            [self setupAreaViewWithType:HTAreaChoiceTypeStart];
            [self setTabViewWithIndex:0];
            
        }
            break;
        case 114://车型车长
        {
            [self removeAreaChoiceView];
            if (!self.truckLengthTypeView) {
                [self setupTruckLengthTypeView];
                [self setTabViewWithIndex:2];
            }else{
                [self removeTruckLengthTypeView];
                [self setTabViewWithIndex:3];
            }
        }
            break;
        default:
            break;
    }
}
//选中起始地，目的地，车长车型部分
- (void)setTabViewWithIndex:(NSInteger)index{
    switch (index) {
        case 0://起始地
        {
            [self setTabViewSelected:YES withImageView:self.startImageView withLabel:self.startLabel];
            [self setTabViewSelected:NO withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
        }
            break;
        case 2://车长车型
        {
            [self setTabViewSelected:NO withImageView:self.startImageView withLabel:self.startLabel];
            [self setTabViewSelected:YES withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
        }
            break;
        case 3://均不选中
        {
            [self setTabViewSelected:NO withImageView:self.startImageView withLabel:self.startLabel];
            [self setTabViewSelected:NO withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
        }
            break;
        default:
            break;
    }
}
- (void)setTabViewSelected:(BOOL)selected withImageView:(UIImageView *)imageView withLabel:(UILabel *)label{
    if (selected) {
        imageView.image = [[UIImage imageNamed:@"arrow_solid_up"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imageView.tintColor = kBlueColor;
        label.textColor = kBlueColor;
    }else{
        imageView.image = [[UIImage imageNamed:@"arrow_solid_down"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imageView.tintColor = [UIColor blackColor];
        label.textColor = [UIColor blackColor];
    }
}
#pragma mark -------- 处理弹框选择出发地目的地的操作
//出发地目的地弹框View
- (void)setupAreaViewWithType:(HTAreaChoiceType)type{
    if (!self.areaChoiceView) {
        self.areaChoiceView = [[HTAreaChoiceView alloc]initWithFrame:CGRectMake(0, self.startView.bottom, kHTScreenWidth, kHTScreenHeight - self.startView.bottom - kHTNavicationBarAndStatusBar)];
        self.areaChoiceView.areaChoiceType = type;
        self.areaChoiceView.delegate = self;
        __weak __typeof(self)weakSelf = self;
        self.areaChoiceView.blockCallBack = ^{
            [weakSelf removeAreaChoiceView];
            [weakSelf setTabViewWithIndex:3];
        };
        [self.view addSubview:self.areaChoiceView];
    }
}
//移除弹框，出发地目的地
- (void)removeAreaChoiceView{
    if (self.areaChoiceView) {
        [self.areaChoiceView removeFromSuperview];
        self.areaChoiceView = nil;
    }
}
//代理
- (void)didChoiceItemWithAreaModel:(HTAreaModel *)areaModel currentIndex:(NSInteger)currentIndex areaChoiceType:(HTAreaChoiceType)areaChoiceType{
    
    if (areaModel.areaType == HTAreaTypeNo || areaModel.areaType == HTAreaTypeArea) {
        [self removeAreaChoiceView];
        [self setTabViewWithIndex:3];
        NSString *place = [HTUtils placePostStringWith:areaModel];
        if (areaChoiceType == HTAreaChoiceTypeStart) {//出发地
            self.startLabel.text = areaModel.title;
            self.startAddress = place;
            //调用刷新网络请求
            [self panMap];
            [self netLoadData];
        }
    }
}
- (void)didChoiceItemWithHistory:(HTAreaModel *)areaModel areaChoiceType:(HTAreaChoiceType)areaChoiceType{
    NSString *place = [HTUtils placePostStringWith:areaModel];
    //调用刷新网络请求
    [self removeAreaChoiceView];
    [self setTabViewWithIndex:3];
    if (areaChoiceType == HTAreaChoiceTypeStart) {//出发地
        self.startLabel.text = areaModel.title;
        self.startAddress = place;
        //调用刷新网络请求
        [self panMap];
        [self netLoadData];
    }
}
#pragma mark --- 处理弹框车长车型
- (void)setupTruckLengthTypeView{
    if (!self.truckLengthTypeView) {
        self.truckLengthTypeView = [[HTScanTruckType alloc]initWithFrame:CGRectMake(0, self.startView.bottom, kHTScreenWidth, kHTScreenHeight - self.startView.bottom - kHTNavicationBarAndStatusBar)];
        self.truckLengthTypeView.delegate = self;
        __weak __typeof(self)weakSelf = self;
        self.truckLengthTypeView.blockCallBack = ^{
            [weakSelf removeTruckLengthTypeView];
            [weakSelf setTabViewWithIndex:3];
        };
        [self.view addSubview:self.truckLengthTypeView];
    }
}
//移除弹框，车长车型
- (void)removeTruckLengthTypeView{
    if (self.truckLengthTypeView) {
        [self.truckLengthTypeView removeFromSuperview];
        self.truckLengthTypeView = nil;
    }
}
- (void)didClickConformWithLengths:(NSMutableArray *)lengthsData TruckType:(HTTruckTypeModel *)truckType isLessThanTruck:(BOOL)isLessThanTruck{
    self.selectedLengthData = lengthsData;
    self.selectedTruckType = truckType;
    self.isLessThanTruck = isLessThanTruck;
    NSString *total = @"";
    total = [NSString stringWithFormat:@"%@,%@",total,[HTUtils sortLengthDataDisplayStringWithArray:lengthsData]];
    NSInteger index = 1;
    if ([total isEqualToString:@",不限车长"]) {
        total = @"";
        index = 0;
    }
    if (!(truckType.truckTypeModelType == TruckTypeModelTypeUnlimited)) {
        if (index < 2) {
            total = [NSString stringWithFormat:@"%@,%@",total,truckType.title];
            index++;
        }
    }
    if (total.length <= 0) {
        total = @"车长车型";
    }else{
        total = [total substringFromIndex:1];
    }
    if (self.isLessThanTruck) {
        self.isEmptyString = @"1";
    }else{
        self.isEmptyString = @"0";
    }
    self.truckTypeLabel.text = total;
    [self removeTruckLengthTypeView];
    [self setTabViewWithIndex:3];
    //调用刷新网络请求
    [self netLoadData];
}
- (void)panMap{
    AMapGeocodeSearchRequest *geo = [[AMapGeocodeSearchRequest alloc] init];
    geo.address = self.startAddress;
    [self.search AMapGeocodeSearch:geo];
    
}
#pragma mark --- 网络请求
- (void)netLoadData{
    [self startHud];
    [HTHttpRequestManager requestTruckListMapWithCarstate:self.startAddress length:self.lengthString cargotype:self.truckTypeString state:self.isEmptyString success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"搜索Map车辆列表：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"搜索车辆列表请求失败"];
            return;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        self.dataSource = [HTSearchTruckModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [self clear];
        [self addAnotationViewByData];
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"搜索车辆列表请求失败"];
    }];
}
//添加气泡
- (void)addAnotationViewByData{
   
    for (HTSearchTruckModel *searchModel in self.dataSource) {
        [self addAnnotationWithModel:searchModel];
    }
    [self.mapView showAnnotations:self.annotations animated:YES];
}
- (void)addAnnotationWithModel:(HTSearchTruckModel *)model
{
    HTMyAnnotation *item = [[HTMyAnnotation alloc]init];
    item.ID = model.carid;
    item.state = model.state;
    item.coordinate = CLLocationCoordinate2DMake((CLLocationDegrees)[model.lat doubleValue], (CLLocationDegrees)[model.lng doubleValue]);
    [self.mapView addAnnotation:item];
    [self.annotations addObject:item];
}
- (void)clear{
    if (self.annotations.count >0) {
          [self.mapView removeAnnotations:self.annotations];
    }
}
@end

@implementation HTSearchTruckModel

@end

